package com.yumi.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect // 声明这是一个切面
@Component  // 结合扫描包，产生bean对象注入IoC容器中
public class TransactionAspect {
    private static final Logger log = LoggerFactory.getLogger(TransactionAspect.class);

    //定义切入点
    @Pointcut("execution(* com.yumi.service..*.*(..))")
    public void pt() {}

    //通过方法名进行引用
    @Before("pt()")
    public void before(JoinPoint jp) {
        log.info("[TransactionAspect 前置增强] 模拟打开数据库连接并开启事务。。。");
        log.info("SqlSession sqlSession = MyBatisUtil.createSqlSession(false);");
    }

    @AfterReturning(value = "pt()",returning = "result")
    public void afterReturning(JoinPoint jp, boolean result) {
        log.info("[TransactionAspect 后置增强] 模拟正常完成业务提交事务");
        log.info("sqlSession.commit();");
    }

    @AfterThrowing(value = "pt()",throwing = "e")
    public void afterThrowing(JoinPoint jp, Exception e) {
        log.info("[TransactionAspect 异常抛出增强] 模拟业务异常回滚事务，异常信息为：" + e.getMessage());
        log.info("sqlSession.rollback();");
    }

    @After("pt()")
    public void after(JoinPoint jp) {
        log.info("[TransactionAspect 最终增强] 模拟业务完成释放资源。。。");
        log.info("MyBatisUtil.closeSqlSession();");
    }

//    // 用于保存方法执行结果
//    private ThreadLocal<Boolean> methodResult = new ThreadLocal<>();
//
//    /**
//     * 前置增强-打开数据库连接开启事务
//     */
//    @Before("execution(* com.yumi.service..*.*(..))")
//    public void before(JoinPoint jp) {
//        log.info("[TransactionAspect 前置增强] 模拟打开数据库连接并开启事务。。。");
//        log.info("SqlSession sqlSession = MyBatisUtil.createSqlSession(false);");
//    }
//
//    /**
//     * 后置增强-提交事务并关闭数据库连接
//     */
//    @AfterReturning(value = "execution(* com.yumi.service..*.*(..))", returning = "result")
//    public void afterReturning(JoinPoint jp, boolean result) {
//        // 正常返回
//        methodResult.set(result);
//        log.info("[TransactionAspect 后置增强] 模拟正常完成业务提交事务");
//        log.info("sqlSession.commit();");
//    }
//
//    /**
//     * 异常抛出增强-执行事务回滚
//     */
//    @AfterThrowing(value = "execution(* com.yumi.service..*.*(..))", throwing = "e")
//    public void afterThrowing(JoinPoint jp, Exception e) {
//        methodResult.set(false);
//        log.info("[TransactionAspect 异常抛出增强] 模拟业务异常回滚事务，异常信息为：" + e.getMessage());
//        log.info("sqlSession.rollback();");
//    }
//
//    /**
//     * 最终增强-关闭数据库连接
//     */
//    @After("execution(* com.yumi.service..*.*(..))")
//    public Object after(JoinPoint jp) {
//        try{
//            log.info("[TransactionAspect 最终增强] 模拟业务完成释放资源。。。");
//            log.info("MyBatisUtil.closeSqlSession();");
//            // 返回结果
//            return methodResult.get();
//        }finally {
//            methodResult.remove();  // 清除ThreadLocal变量
//        }
//    }
}
